package com.blb.search_service.service;

import com.blb.search_service.entity.PageResult;
import com.blb.search_service.entity.Spu;
import com.blb.search_service.repo.SpuRepository;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;

@Service
public class SpuService {

    @Autowired
    private SpuRepository spuRepository;

    public PageResult<Spu> page(String key,long page){
        NativeSearchQueryBuilder builder = new NativeSearchQueryBuilder();
        //填写了关键字就按关键字进行搜索
        if(key != null && key.length() > 0){
            builder.withQuery(QueryBuilders.multiMatchQuery(key,"title","subTitle"));
        }
        int current = 0;
        if(page > 0){
            current = (int) (page - 1);
        }
        builder.withPageable(PageRequest.of(current,10))
                .withSort(SortBuilders.fieldSort("id").order(SortOrder.ASC));
        Page<Spu> res = spuRepository.search(builder.build());
        return new PageResult(page,res.getTotalElements(),10L,res.getContent());
    }
}
